import store from "@/store";
// import { Notification, Message } from "element-ui";
const state = {
  isConnect: false,
  user_socket: null,
  tenant_socket: null,
  connection_num: 0,
  tenant_connection_num: 0
};

const mutations = {
  SET_IS_CONNECT: (state, isConnect) => {
    state.isConnect = isConnect;
  },
  SET_USER_SOCKET: (state, user_socket) => {
    state.user_socket = user_socket;
  },
  SET_TENANT_SOCKET: (state, tenant_socket) => {
    state.tenant_socket = tenant_socket;
  },
  ADD_CONNECTION_NUM: (state, connection_num) => {
    state.connection_num += connection_num || 1;
  },
  ADD_TENANT_CONNECTION_NUM: (state, tenant_connection_num) => {
    state.tenant_connection_num += tenant_connection_num || 1;
  }
};
const actions = {
  init({ dispatch, commit, rootState }) {
    if (typeof (WebSocket) === "undefined") {
      this.$notify({
        title: "提示",
        message: "当前浏览器无法接收实时信息，请使用谷歌浏览器！",
        type: "warning",
        duration: 0
      });
    } else {
      dispatch("init_user_socket");
    }
  },
  init_user_socket({ dispatch, commit, rootState }) {
    if (!state.user_socket || state.user_socket.readyState === 3) {
      state.user_socket = new WebSocket(getBaseUrl());
      state.user_socket.onopen = () => {
        commit("SET_IS_CONNECT", true);
        console.log("连接" + state.user_socket.url);
      };
      state.user_socket.onmessage = onMessage;
      state.user_socket.onclose = (e) => {
        if (state.isConnect && state.connection_num < 3) {
          commit("ADD_CONNECTION_NUM");
        }
      };
      state.user_socket.onerror = (event) => {
        console.log(event);
      };
    }
  },
  closeSocket({ dispatch, commit, state }) {
    commit("SET_IS_CONNECT", false);
    if (state.user_socket) {
      state.user_socket.close();
    }
    if (state.tenant_socket) {
      state.tenant_socket.close();
    }
  }
};

function getBaseUrl() {
  const ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";
  // return ws_scheme + "://" + window.location.host + process.env.VUE_APP_BASE_API + "/";
  return ws_scheme + "://" + window.location.host + process.env.VUE_APP_BASE_API;
}
function onMessage(evt) {
  const data = JSON.parse(JSON.parse(evt.data));
  console.log("socket-data", JSON.parse(JSON.parse(evt.data)));
  // 推送同步信息
  if (data.app === "cloudadmin") {
    const event = data.event;
    const Msg = data.msg;
    const Type = data.Type;
    state.msg = data.msg;
    const Component = data.component;
    if (!event) {
      Component({
        title: "提示",
        message: Msg,
        type: Type,
        position: "top-right",
        duration: 4000
      });
      store.commit("app/SET_SYNC_STATUS", new Date());
    }
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
};
